<template>
  <div class="w-full h-full bg-[#ccc] flex items-center justify-center">
    <div class="w-[50%] h-[70%] p-[20px] bg-[#fff] flex flex-col">
      <div
        class="bg-[#3ed1c205] flex-1 w-full border border-[#3ed1c2] rounded-[6px] p-[10px] overflow-y-auto"
      >
        <div
          class="border-1 max-w-[50%] min-h-[40px] flex items-center justify-center leading-7 px-2 mb-[10px] rounded-[6px] text-[16px] break-words clear-both"
          v-for="(item, index) in messages"
          :key="index"
          :class="
            item.identity == 'me'
              ? 'bg-[#d9fdd3] float-right'
              : 'bg-[#e6f7ff] float-left'
          "
        >
          <span v-if="item.identity == 'me'">{{ item.message }}</span>
          <span v-else>{{ item.message }}</span>
        </div>
      </div>
      <div class="w-full flex items-center pt-[20px]">
        <el-input
          class="flex-1 mr-2"
          v-model="inputMessage"
          placeholder="请输入"
        />
        <el-button @click="sendMessage" type="primary">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";
import { Buffer } from "buffer";

export default defineComponent({
  /*
  请打开src\utils\webSocket.js建立webSocket连接
  然后开始使用
   */
  setup() {
    const messages = ref<any>([]);
    const inputMessage = ref<string>("");
    const socket = new WebSocket("ws://localhost:8086");

    // 连接成功时触发
    socket.addEventListener("open", () => {
      console.log("WebSocket连接已建立");
      // 向服务器发送消息
      socket.send("Hello, WebSocket Server!");
    });

    // 接收到服务器消息时触发
    socket.addEventListener("message", (event) => {
      console.log(`收到消息：${event.data}`);
    });

    // 连接关闭时触发
    socket.addEventListener("close", () => {
      console.log("WebSocket连接已关闭");
    });
    // 发生错误时触发
    socket.addEventListener("error", (error) => {
      console.error(`WebSocket错误：${error}`);
    });
    socket.onmessage = function (event) {
      // 在这里处理接收到的消息
      let message = event.data;
      let obj = JSON.parse(message);
      if (obj.message && !obj.type) {
        messages.value.push(obj);
      } else {
        const buf = Buffer.from(obj.data);
        const str = buf.toString();
        const obj2 = JSON.parse(str);
        messages.value.push(obj2);
      }
    };
    function sendMessage() {
      if (inputMessage.value.trim()) {
        // 向服务器发送消息
        let data = { message: inputMessage.value, identity: "me" };
        socket.send(JSON.stringify(data));
        inputMessage.value = ""; // 清空输入框
      }
    }
    return {
      messages,
      inputMessage,
      sendMessage,
      socket,
    };
  },
});
</script>
